package com.wangxiang.sys.manage.controller;

import java.io.FileNotFoundException;
import java.util.*;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.wangxiang.common.utils.PageEntity;
import com.wangxiang.sys.manage.dao.AuthDao;
import com.wangxiang.sys.manage.entity.AuthEntity;
import com.wangxiang.sys.manage.entity.ImgEntity;
import com.wangxiang.sys.manage.entity.UserEntity;
import com.wangxiang.sys.manage.feign.ThirdFeign;
import com.wangxiang.sys.manage.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wangxiang.sys.manage.service.UserService;
import com.wangxiang.common.utils.PageUtils;
import com.wangxiang.common.utils.R;



/**
 * 
 *
 * @author wangxiang
 * @email 2293672863@qq.com
 * @date 2022-03-06 18:58:24
 */
@RestController
@RequestMapping("sys/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    ThirdFeign thirdFeign;
    @Autowired
    private AuthDao authDao;


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);
        return R.ok().put("page", page);
    }
    @RequestMapping("page")
    public R page(@RequestBody PageEntity pageEntity){
        PageEntity page = userService.page(pageEntity);
        return R.ok().put("page",page);
    }
    @RequestMapping("img")
    public R img(@RequestBody HashMap<String , Object> map){
        System.out.println("map"+map);
        UserEntity entity = new UserEntity();
        String nullStr = "";
        if (map.get("userName")==null|nullStr.equals(map.get("userName"))|map.get("userName")==" "){
            return R.error("请输入用户名");
        }
        entity.setLoginId(map.get("userName").toString());
        //用户光标改变时没有数据，
        if (entity.getLoginId()==null|entity.getLoginId().equals("")){
            return R.ok().put("img",null);
        }
        String img = userService.img(entity.getLoginId());
        return R.ok().put("img",img);

    }
    @RequestMapping("search")
    public R search(@RequestBody HashMap<String,String> map){
      if (map.get("userId")==null|map.get("userId")==""){
          return R.error("请输入用户id查询查询，不可查询null");
      }

      try {
          int userId = Integer.valueOf(map.get("userId"));
          List<UserEntity> list = userService.list(userId);
          System.out.println(list);
          if (list.size()==0){
              return R.error("管路员不存在");
          }else {
              return R.ok().put("list",list);
          }
      }catch (NumberFormatException n){
          return R.error("请输入管理id,请输入数值");
      }

    }
    @RequestMapping("selectByLoginId")
    public R selectbyLoginId(@RequestBody HashMap<String,String> map){
        if (map.get("loginId")==null|map.get("loginId")==""){
            return R.ok();
        }
        UserEntity entityByLoginId = userService.getEntityByLoginId(map.get("loginId"));
        if (entityByLoginId!=null){
            return R.error("用户名已存在");
        }
        return R.ok();
    }
    @RequestMapping("add")
    public R add(@RequestBody HashMap<String,Object> map){
        String nullStr = "";
        String nullStrs = " ";
        String email = ".com";
        if (nullStr.equals(map.get("loginId"))|map.get("loginId")==null|nullStrs.equals(map.get("loginId"))){
            return R.error("账号为空");
        }
        if(nullStr.equals(map.get("password"))|map.get("password")==null|nullStrs.equals(map.get("password"))){
            return R.error("密码为空");
        }
        if (nullStr.equals(map.get("email"))|map.get("email")==null|nullStrs.equals(map.get("email"))){
            return R.error("邮箱为空");
        }
        if (nullStr.equals(map.get("mobail"))|map.get("mobail")==null|nullStrs.equals(map.get("mobail"))){
            return R.error("电话为空");
        }
        //类型格式校验，邮箱，价格
        if (!map.get("email").toString().contains(email)){
            return R.error("邮箱格式不正确");
        }
        //电话校验
        System.out.println(map.get("mobail"));

      try{
          Long.valueOf(map.get("mobail").toString());
      }catch (NumberFormatException numberFormatException){
          return R.error("电话必须是数值");
      }
      //查询账号是否存在
        List<UserEntity> list = userService.entityList();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getLoginId().equals(map.get("loginId"))){
                return R.error("账号已存在");
            }
        }
        //发送邮箱，测试邮箱是否存在
        map.put("toEmail",map.get("email"));

        boolean mailaudit = thirdFeign.mailaudit(map);
        if (!mailaudit){
            return R.error("邮箱不存在");
        }



        int add = userService.add(map);
//        System.out.println("结果"+add);
        if (add==0){
            return R.error("添加失败，系统错误，如果已经添加成功请查看角色是否添加成功");
        }

        HashMap<String, Object> thirdMap = new HashMap<>();
        thirdMap.put("toEmail",map.get("email"));
        thirdMap.put("loginId",map.get("loginId"));
        thirdMap.put("password",map.get("password"));
        thirdMap.put("time", DateUtil.now());
        thirdMap.put("role",map.get("role"));
        thirdFeign.mailTest(thirdMap);

        return R.ok().put("msg","管理员添加成功,邮件已发送").put("code",800);
    }

    @RequestMapping("maxupdate")
    public R maxUpdate(@RequestBody UserEntity userEntity){
        String nullStr = "";

        if (userEntity.getLoginId()==null|nullStr.equals(userEntity.getLoginId())){
            return R.error("你并未填写登录");
        }
        if (userEntity.getPassword()==null|nullStr.equals(userEntity.getPassword())){
            return R.error("你并未填写密码");
        }
        UserEntity entityByLoginId = userService.getEntityByLoginId(userEntity.getLoginId());
        if (entityByLoginId!=null){
            if (entityByLoginId.getUserId()!=userEntity.getUserId()){
                System.out.println("id"+entityByLoginId.getUserId()+"/"+userEntity.getUserId());
                return R.error("该用户名已存在");
            }
        }
        if (userEntity.getEmail()!=null|!nullStr.equals(userEntity.getEmail())){
            if (!userEntity.getEmail().contains(".com")){
                return R.error("邮箱格式错误");
            }
        }


        if (!nullStr.equals(userEntity.getMobail())&userEntity.getMobail()!=null){
            try {
                long mobail = Long.valueOf(userEntity.getMobail());
            }catch (NumberFormatException n){
                return R.error("号码必须是数值");
            }
        }
        int i = userService.updateEntity(userEntity);
        if (i==0){
            return R.error("修改失败");
        }


        return R.ok().put("msg","修改管理员信息成功").put("code",800);
    }

    //失效
    @RequestMapping("invalid")
    public R invalid(@RequestBody Integer userId){
        UserEntity invalid = userService.invalid(userId);
        if (invalid==null){
            return R.error("失效工号失败，系统错误");
        }
        return R.ok().put("msg","你已成功失效工号："+invalid.getUserId()+"、管理员："+invalid.getLoginId()).put("code",800);
    }


    @RequestMapping("recover")
    public R recover(@RequestBody Integer userId){
        UserEntity recover = userService.recover(userId);
        if (recover==null){
            return R.error("工号恢复使用失败，系统错误");
        }
        return R.ok().put("msg","工号："+recover.getUserId()+"/"+recover.getLoginId()+"已恢复使用").put("code",800);
    }
    @RequestMapping("order/list")
    public List<HashMap<String , Object>> orderList(@RequestBody List<HashMap<String , Object>> maps){
        List<HashMap<String, Object>> list = userService.userInfoMap(maps);
        return list;
    }
    @RequestMapping("line")
    public R lineStatus(@RequestBody Integer userId){
        userService.lineStatus(userId,1);
        return R.ok();
    }

    @RequestMapping("line/list")
    public R userLineList(){
        List<HashMap<String, Object>> list = userService.userLineList();
        return R.ok().put("list",list);
    }
    @RequestMapping("info")
    public R info(@RequestBody Integer id){
        HashMap<String, Object> info = userService.info(id);
        return R.ok().put("info",info);
    }
    @RequestMapping("info/test")
    public R infoTest(){
        List<AuthEntity> authEntities = authDao.getList();
        return R.ok().put("list",authEntities);
    }
    @RequestMapping("update/info")
    public R updateLoginIdPassword(@RequestBody HashMap<String , Object> map){
        String nullStr = "";
        Object psw = map.get("psw");
        Object repsw = map.get("repsw");
        if (nullStr.equals(psw)|psw==null|psw==" "){
            return R.error("请输入原始密码");
        }
        if (nullStr.equals(repsw)|repsw==null|repsw==" "){
            return R.error("请输入新密码");
        }
        UserEntity entity = userService.getEntityByUserId(Integer.valueOf(map.get("userId").toString()));

        if (!entity.getPassword().equals(psw)){
            return R.error("原始密码不正确");
        }

        if (repsw==entity.getPassword()|entity.getPassword().equals(repsw)){
            return R.error("旧密码与新密码一致");
        }
        String repassword = repsw.toString();
        String replace = repassword.replace(" ", "");
        if (replace.getBytes().length<6){
            return R.error("密码长度不够，最低6位");
        }

        int userId = userService.updatePassword(Integer.valueOf(map.get("userId").toString()), replace);
        if (userId==0){
            return R.error("修改密码错误");
        }


        //表单校验
        return R.ok().put("msg","你已成功更新密码,请重新登录").put("code",800);
    }
    @RequestMapping("info/list")
    public R userInfoList(){
        List<UserEntity> userEntities = userService.entityList();
        ArrayList<HashMap<String , Object>> list = new ArrayList<>();
        for (UserEntity userEntity : userEntities) {
            HashMap<String, Object> info = userService.info(userEntity.getUserId());
            list.add(info);
        }
        return R.ok().put("infoList",list);

    }
    @RequestMapping("update/image")
    public R updateImage(@RequestBody HashMap<String ,Object> map){
        int i = userService.updateImage(map);
        if (i==0){
            return R.error("更新失败");
        }
        return R.ok().put("msg","更新头像成功").put("code",800);
    }
    @RequestMapping("update/email/captcha")
    public R updateEmailCaptcha(@RequestBody HashMap<String , Object> map){
        map.put("title","王相的毕业设计管理后台管理员邮箱变更验证码");
        String captcha = RandomUtil.randomString(5);
        String UUID = RandomUtil.randomString(64);
        map.put("text","验证码："+ captcha+"\n"+"3分钟有效");
        boolean b = thirdFeign.emailText(map);
        if (!b){
            return R.error("第三方模块系统异常，请联系超级管理员修改数据表");
        }
        //redis存储uuid
        redisUtils.set("reBingEmailUUID",UUID,180000);
        redisUtils.set("reBingEmailCaptcha",captcha,180000);
        return R.ok().put("msg","验证码已发送致："+map.get("toEmail")).put("code",800).put("UUID",UUID);
    }
    @RequestMapping("update/email/captcha/check")
    public R updateEmailCapthcaCheck(@RequestBody HashMap<String , Object> map){
        Object redisUUID = redisUtils.get("reBingEmailUUID");
        Object redisCaptcha = redisUtils.get("reBingEmailCaptcha");
        if (redisCaptcha==null|redisUUID==null){
//            System.out.println("这里");
            return R.error("验证码超时");
        }
        Object uuid = map.get("UUID");
        Object captcha = map.get("captcha");

//        System.out.println(uuid!=redisUUID);

        String nullStr = "";
        String nullStrs = " ";
        if (captcha==null|nullStr.equals(captcha)|nullStrs.equals(captcha)){
            return R.error("请填写验证码");
        }
        if (uuid==null|redisUUID==null){
            return R.ok("请重新获取验证码");
        }
        if (!uuid.equals(redisUUID)){
            return R.ok("验证码超时");
        }
        if (redisCaptcha==null){
            return R.ok("验证码超时");
        }
        if(!captcha.equals(redisCaptcha)){
            return R.error("验证码错误");
        }
        return R.ok().put("msg","验证码校验成功，请输入新邮箱").put("code",800);

    }
    @RequestMapping("update/email/bing")
    public R reBingEmail(@RequestBody HashMap<String , Object> map){
        String nullStr = "";
        String nullStrs = " ";
        Object email = map.get("toEmail");
        if (email==null|nullStr.equals(email)|nullStrs.equals(email)){
            return R.error("邮箱不能为空");
        }
        if (!email.toString().contains(".com")){
            return R.error("邮箱格式错误");
        }
        int i = userService.updateEmail(map);
        if (i==0){
            return R.error("操作失败，系统错误");
        }
        map.put("title","王相的毕业设计管理后台管理员邮箱变更通知");
        map.put("text","邮箱重新绑定");
        boolean b = thirdFeign.emailText(map);
        if (!b) {
            return R.error("第三方模块错误");
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("toEmail",map.get("email"));
        hashMap.put("title","王相的毕业设计管理后台管理员邮箱变更通知");
        hashMap.put("text","邮箱变更"+"\n"+
                "旧邮箱："+map.get("email")+"\n"+
                "新邮箱："+map.get("toEmail")+"\n"
                );
        boolean b1 = thirdFeign.emailText(hashMap);
        if (!b1){
            return R.error("第三方模块错误");
        }
        return R.ok().put("msg","邮箱已重新绑定").put("code",800);
    }
    @RequestMapping("update/mobile")
    public R updateMobile(@RequestBody HashMap<String , Object> map){
        Object mobile = map.get("mobile");
        String nullStr = "";
        String nullStrs = " ";
        if (mobile==null|nullStr.equals(mobile)|nullStrs.equals(mobile)){
            return R.error("邮箱不能为空");
        }
        //格式校验
        try{
            Long.valueOf(mobile.toString());
        }catch (NumberFormatException numberFormatException){
            return R.error("电话必须数值");
        }
        int i = userService.updateMobile(map);
        if (i==0){
            return R.error("系统错误");
        }
        return R.ok().put("msg","更新电话绑定操作成功").put("code",800);
    }

    @RequestMapping("upgrade/role/audit")
    public R upgradeRole(@RequestBody Integer userId){
        UserEntity entity = userService.getEntityByUserId(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("toEmail","2293672863@qq.com");
        map.put("title","管理后台管理员权限升级申请");
        map.put("text","账号："+entity.getLoginId()+"\n"+
                "系统标识："+entity.getUserId()+"\n"+
                "操作类型：升级权限，升级角色申请"
                );

        boolean b = thirdFeign.emailText(map);
        if (!b){
            return R.error("第三方系统模块错误");
        }
        return R.ok().put("msg","系统已给系统管理员 王相 发送申请，三个工作日内处理该申请，届时会以邮件形式通知").put("code",800);
    }


}
